/*
 * mach_timer.c
 *
 *  Created on: Nov 19, 2011
 *      Author: bendischinger
 */

#include <unistd.h>
#include <float.h>

#include "test_stat.h"

#ifdef __APPLE__

#include <mach/mach.h>
#include <mach/mach_time.h>

test_time_t start_timer(void) {
	return mach_absolute_time();
}

double stop_timer(test_time_t start, int unit) {
    uint64_t end;
    uint64_t elapsed;
    double elapsedUnitTime;
    static mach_timebase_info_data_t sTimebaseInfo;

    // Stop the clock.
    end = mach_absolute_time();

    // Calculate the duration.
    elapsed = end - start;

    // Convert to nanoseconds.

    // If this is the first time we've run, get the timebase.
    // We can use denom == 0 to indicate that sTimebaseInfo is
    // uninitialised because it makes no sense to have a zero
    // denominator is a fraction.

    if ( sTimebaseInfo.denom == 0 ) {
        (void) mach_timebase_info(&sTimebaseInfo);
    }

    // Do the maths. We hope that the multiplication doesn't
    // overflow; the price you pay for working in fixed point.

    elapsedUnitTime = (elapsed * sTimebaseInfo.numer / (double)sTimebaseInfo.denom) * (unit/(double)UNIT_NSEC);

    return elapsedUnitTime;
}

#endif

double convert_time(double time, int from_unit, int to_unit) {
	return (time / from_unit) * to_unit;
}

void init_test_stat(test_stat_t *stat) {
	bzero(stat, sizeof(test_stat_t));
	stat->min_op_time = DBL_MAX;
	stat->min_read_time = DBL_MAX;
	stat->min_write_time = DBL_MAX;
}
